#include <linSlaveTask.h>
#include <ColorMixingTask.h>

TaskState_t        linsTaskState = TASK_STATE_INIT;
LIN_Device_Frame_t activelinsFrame;

LIN_Device_Frame_t lins_cmd_table[] = {
    [0] = {
        .frame_id = 0x06,
        .msg_type = LIN_MSG_TYPE_RX,
        .checksum = LIN_CHECKSUM_CLASSIC,
        .length   = LIN_BUFF_SIZE,
    },
    [1] = {
        .frame_id = 0x0C,
        .msg_type = LIN_MSG_TYPE_TX,
        .checksum = LIN_CHECKSUM_CLASSIC,
        .length   = LIN_BUFF_SIZE,
        .responseValid = true,
    },
};



void hanldeLinMasterCommands(LIN_Device_Frame_t *frame)
{
    if (frame->frame_id == 0x06){
        Color_CMD_Frame_t *color = (Color_CMD_Frame_t *)frame->data;
        switch(color->command){
        case COLOR_CMD_XYY:
          CLM_SetXYY(ROOM_TEMPERATURE, LED0, color->ColorXY.x, color->ColorXY.y, color->ColorXY.Y, (uint16_t)color->ColorXY.transitionTime);
          break;
        case COLOR_CMD_HSL:
          CLM_SetHSL(ROOM_TEMPERATURE, LED0, color->ColorHSL.hue, (uint8_t)color->ColorHSL.saturation, color->ColorHSL.level, (uint16_t)color->ColorHSL.transitionTime);
          break;
        case COLOR_CMD_RGB:
          for (LedNumber_t i = LED0; i <= LED5; i++){
              CLM_SetRGBL(ROOM_TEMPERATURE, i, color->ColorRGB.red, color->ColorRGB.green, color->ColorRGB.blue, color->ColorRGB.level,(uint16_t)color->ColorRGB.transitionTime);
          }
          break;
        case COLOR_CMD_PWM:
          CLM_SetPWMs(LED0, color->ColorPWM.PWM_Red, color->ColorPWM.PWM_Green, color->ColorPWM.PWM_Blue);
          break;
        }
    }else if (frame->frame_id == 0x3C){
        lins_cmd_table[2].responseValid = true;
        for (uint8_t i = 0; i < 8; i++){
          lins_cmd_table[2].data[i] = 0xAA +i;
        }
    }
}

void LIN_Slave_ISR(LIN_Device_Frame_t *frame)
{
    activelinsFrame = *frame;
    TM_PostTask(TASK_ID_LINS);
    hanldeLinMasterCommands(&activelinsFrame);
}

uint8_t times=0;
void LINS_TaskHandler(void)
{
    switch(linsTaskState){
    case TASK_STATE_ACTIVE:
      times++;
      hanldeLinMasterCommands(&activelinsFrame);
      break;
    case TASK_STATE_INIT:
      times=2;
      LINS_Init();
      LINS_RegisterLINS_IRQ(LIN_Slave_ISR);
      LINS_RegisterServices(lins_cmd_table, sizeof(lins_cmd_table)/sizeof(LIN_Device_Frame_t));
      linsTaskState = TASK_STATE_ACTIVE;
      break;
    }
}